{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 资源索引\n",
    "#### Azure语音识别API阅读\n",
    "\n",
    "* [Azure语音识别](https://azure.microsoft.com/zh-cn/services/cognitive-services/speech-to-text/#features)\n",
    "\n",
    "* [Azure REST API](https://docs.microsoft.com/zh-cn/azure/cognitive-services/speech/getstarted/getstartedrest)\n",
    "\n",
    "#### 实践百度语音识别API\n",
    "\n",
    "* [Baidu Speech](http://yuyin.baidu.com/)\n",
    "* [Baidu TTS](http://ai.baidu.com/tech/speech/tts)\n",
    "\n",
    "#### 示例代码见\n",
    "\n",
    "* [github仓库](https://github.com/Baidu-AIP/speech-demo)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### A-1 Baidu Speech ASR\n",
    "\n",
    "* 语音识别（（Automatic Speech Recognition））\n",
    "* 文本转语音 ((Text to speak))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"access_token\":\"24.ca324ff16ecab87be3ba12e1323862b7.2592000.1607936060.282335-22971991\",\"session_key\":\"9mzdWBHOy11cqGf+r7VMT3keFpUYz9S2VVPkKDop+V8siC6MxsnRh+emXsWQAAs76NBiIDjERnLq6RLym4EkFvzst\\/s\\/tg==\",\"scope\":\"audio_voice_assistant_get brain_enhanced_asr audio_tts_post brain_speech_realtime public brain_all_scope picchain_test_picchain_api_scope brain_asr_async wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test\\u6743\\u9650 vis-classify_flower lpq_\\u5f00\\u653e cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_\\u5f00\\u653eScope vis-ocr_\\u865a\\u62df\\u4eba\\u7269\\u52a9\\u7406 idl-video_\\u865a\\u62df\\u4eba\\u7269\\u52a9\\u7406 smartapp_component\",\"refresh_token\":\"25.52d90c997b81afbe79d59eaa9e773a9a.315360000.1920704060.282335-22971991\",\"session_secret\":\"99e6834d839983896b9ee3d7cc1014b7\",\"expires_in\":2592000}\n",
      "\n",
      "{'access_token': '24.ca324ff16ecab87be3ba12e1323862b7.2592000.1607936060.282335-22971991', 'session_key': '9mzdWBHOy11cqGf+r7VMT3keFpUYz9S2VVPkKDop+V8siC6MxsnRh+emXsWQAAs76NBiIDjERnLq6RLym4EkFvzst/s/tg==', 'scope': 'audio_voice_assistant_get brain_enhanced_asr audio_tts_post brain_speech_realtime public brain_all_scope picchain_test_picchain_api_scope brain_asr_async wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component', 'refresh_token': '25.52d90c997b81afbe79d59eaa9e773a9a.315360000.1920704060.282335-22971991', 'session_secret': '99e6834d839983896b9ee3d7cc1014b7', 'expires_in': 2592000}\n",
      "SUCCESS WITH TOKEN: 24.ca324ff16ecab87be3ba12e1323862b7.2592000.1607936060.282335-22971991 ; EXPIRES IN SECONDS: 2592000\n",
      "url is http://vop.baidu.com/server_api?cuid=123456PYTHON&token=24.ca324ff16ecab87be3ba12e1323862b7.2592000.1607936060.282335-22971991&dev_pid=1537\n",
      "header is {'Content-Type': 'audio/m4a; rate=16000', 'Content-Length': 448429}\n",
      "Request time cost 1.211052\n",
      "{\"corpus_no\":\"6894900242036985003\",\"err_msg\":\"success.\",\"err_no\":0,\"result\":[\"用那种方式让我们去考虑别人的想法，完成那些，或许可以使后代受益的工作就是这些人永远都不会意识到你为什么所做的一切没关系的，因为你会知道并意识到你生命的独特性和重要性，谢谢。\"],\"sn\":\"329039720661605344060\"}\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# 1. 写入api-key和secret-key （修改）\n",
    "\n",
    "API_KEY = '7PUwvRhlT1XfWfnGt5YVBKwI'\n",
    "SECRET_KEY = 'CEa74p63SNfn9q2etV8PrTr9g7eEZFXq'\n",
    "\n",
    "# 调用固定模块\n",
    "\n",
    "import sys\n",
    "import json\n",
    "import time\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "\n",
    "    timer = time.perf_counter\n",
    "else:\n",
    "    import urllib2\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "\n",
    "    if sys.platform == \"win32\":\n",
    "        timer = time.clock\n",
    "    else:\n",
    "        # On most other platforms the best timer is time.time()\n",
    "        timer = time.time\n",
    "        \n",
    "# 需要识别的文件 （修改）\n",
    "AUDIO_FILE = 'speech_tape.m4a' # 只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "# 文件格式\n",
    "FORMAT = AUDIO_FILE[-3:];  # 文件后缀只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "\n",
    "CUID = '123456PYTHON';\n",
    "# 采样率\n",
    "RATE = 16000;  # 固定值\n",
    "\n",
    "# 普通版\n",
    "\n",
    "DEV_PID = 1537;  # 1537 表示识别普通话，使用输入法模型。根据文档填写PID，选择语言及识别模型 （可修改），1737-英语\n",
    "ASR_URL = 'http://vop.baidu.com/server_api' # (固定)\n",
    "SCOPE = 'audio_voice_assistant_get'  # 有此scope表示有asr能力，没有请在网页里勾选，非常旧的应用可能没有\n",
    "\n",
    "#测试自训练平台需要打开以下信息， 自训练平台模型上线后，您会看见 第二步：“”获取专属模型参数pid:8001，modelid:1234”，按照这个信息获取 dev_pid=8001，lm_id=1234\n",
    "# DEV_PID = 8001 ;   \n",
    "# LM_ID = 1234 ;\n",
    "\n",
    "# 极速版 打开注释的话请填写自己申请的appkey appSecret ，并在网页中开通极速版（开通后可能会收费）\n",
    "\n",
    "#DEV_PID = 80001\n",
    "#ASR_URL = 'http://vop.baidu.com/pro_api'\n",
    "#SCOPE = 'brain_enhanced_asr'  # 有此scope表示有asr能力，没有请在网页里开通极速版\n",
    "\n",
    "# 忽略scope检查，非常旧的应用可能没有\n",
    "# SCOPE = False\n",
    "\n",
    "\n",
    "# 极速版\n",
    "\n",
    "class DemoError(Exception):\n",
    "    pass\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN start \"\"\"\n",
    "\n",
    "TOKEN_URL = 'http://openapi.baidu.com/oauth/2.0/token'\n",
    "\n",
    "\n",
    "def fetch_token():\n",
    "    params = {'grant_type': 'client_credentials',\n",
    "              'client_id': API_KEY,\n",
    "              'client_secret': SECRET_KEY}\n",
    "    post_data = urlencode(params)\n",
    "    if (IS_PY3):\n",
    "        post_data = post_data.encode('utf-8')\n",
    "    req = Request(TOKEN_URL, post_data)\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "        print('token http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    if (IS_PY3):\n",
    "        result_str = result_str.decode()\n",
    "\n",
    "    print(result_str)\n",
    "    result = json.loads(result_str)\n",
    "    print(result)\n",
    "    if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "        if SCOPE and (not SCOPE in result['scope'].split(' ')):  # SCOPE = False 忽略检查\n",
    "            raise DemoError('scope is not correct')\n",
    "        print('SUCCESS WITH TOKEN: %s ; EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN end \"\"\"\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    token = fetch_token()\n",
    "\n",
    "    \"\"\"\n",
    "    httpHandler = urllib2.HTTPHandler(debuglevel=1)\n",
    "    opener = urllib2.build_opener(httpHandler)\n",
    "    urllib2.install_opener(opener)\n",
    "    \"\"\"\n",
    "\n",
    "    speech_data = []\n",
    "    with open(AUDIO_FILE, 'rb') as speech_file:\n",
    "        speech_data = speech_file.read()\n",
    "    length = len(speech_data)\n",
    "    if length == 0:\n",
    "        raise DemoError('file %s length read 0 bytes' % AUDIO_FILE)\n",
    "\n",
    "    params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID}\n",
    "    #测试自训练平台需要打开以下信息\n",
    "    #params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID, 'lm_id' : LM_ID}\n",
    "    params_query = urlencode(params);\n",
    "\n",
    "    headers = {\n",
    "        'Content-Type': 'audio/' + FORMAT + '; rate=' + str(RATE),\n",
    "        'Content-Length': length\n",
    "    }\n",
    "\n",
    "    url = ASR_URL + \"?\" + params_query\n",
    "    print(\"url is\", url);\n",
    "    print(\"header is\", headers)\n",
    "    # print post_data\n",
    "    req = Request(ASR_URL + \"?\" + params_query, speech_data, headers)\n",
    "    try:\n",
    "        begin = timer()\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "        print(\"Request time cost %f\" % (timer() - begin))\n",
    "    except  URLError as err:\n",
    "        print('asr http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "\n",
    "    if (IS_PY3):\n",
    "        result_str = str(result_str, 'utf-8')\n",
    "    print(result_str)\n",
    "    with open(\"result.txt\", \"w\") as of:\n",
    "        of.write(result_str)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### A-2 Baidu TTS\n",
    "\n",
    "* 语音合成（Text-to-Speach）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "fetch token begin\n",
      "{\"access_token\":\"24.66ac2660b6c4ff5d2c3ecb91f9303125.2592000.1607936745.282335-22971991\",\"session_key\":\"9mzdDcBsbz\\/BsqER43dJinhBzSPQmpzUirzmOLZ53LT1Q43zLuZ74\\/kfTY3tS9J\\/QIaBC2\\/OVwAsGhulMgDriu2tA7CCVQ==\",\"scope\":\"audio_voice_assistant_get brain_enhanced_asr audio_tts_post brain_speech_realtime public brain_all_scope picchain_test_picchain_api_scope brain_asr_async wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test\\u6743\\u9650 vis-classify_flower lpq_\\u5f00\\u653e cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_\\u5f00\\u653eScope vis-ocr_\\u865a\\u62df\\u4eba\\u7269\\u52a9\\u7406 idl-video_\\u865a\\u62df\\u4eba\\u7269\\u52a9\\u7406 smartapp_component\",\"refresh_token\":\"25.3577048396f52867622b6a536e433a80.315360000.1920704745.282335-22971991\",\"session_secret\":\"26e522da5e0c274efe7f4cbcda14b847\",\"expires_in\":2592000}\n",
      "\n",
      "{'access_token': '24.66ac2660b6c4ff5d2c3ecb91f9303125.2592000.1607936745.282335-22971991', 'session_key': '9mzdDcBsbz/BsqER43dJinhBzSPQmpzUirzmOLZ53LT1Q43zLuZ74/kfTY3tS9J/QIaBC2/OVwAsGhulMgDriu2tA7CCVQ==', 'scope': 'audio_voice_assistant_get brain_enhanced_asr audio_tts_post brain_speech_realtime public brain_all_scope picchain_test_picchain_api_scope brain_asr_async wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component', 'refresh_token': '25.3577048396f52867622b6a536e433a80.315360000.1920704745.282335-22971991', 'session_secret': '26e522da5e0c274efe7f4cbcda14b847', 'expires_in': 2592000}\n",
      "SUCCESS WITH TOKEN: 24.66ac2660b6c4ff5d2c3ecb91f9303125.2592000.1607936745.282335-22971991 ; EXPIRES IN SECONDS: 2592000\n",
      "这是token: 24.66ac2660b6c4ff5d2c3ecb91f9303125.2592000.1607936745.282335-22971991\n",
      "这是tex: %E5%85%B6%E5%AE%9E%E5%BE%88%E4%B9%85%E4%BB%A5%E5%89%8D%E6%88%91%E5%B0%B1%E7%9F%A5%E9%81%93%E8%87%AA%E5%B7%B1%E5%BA%94%E8%AF%A5%E6%80%8E%E6%A0%B7%E9%80%89%E6%8B%A9%EF%BC%8C%E5%8F%AA%E6%98%AF%E4%B8%80%E7%9B%B4%E6%97%A0%E6%B3%95%E4%B8%8B%E5%86%B3%E5%BF%83%E8%88%8D%E5%BC%83%E6%A2%A6%E6%83%B3%E3%80%82%E5%88%B0%E7%8E%B0%E5%9C%A8%EF%BC%8C%E6%88%91%E4%BE%9D%E7%84%B6%E4%B8%8D%E7%9F%A5%E9%81%93%E6%80%8E%E6%A0%B7%E6%89%8D%E8%83%BD%E5%81%9A%E5%88%B0%E8%BF%99%E4%B8%80%E7%82%B9%E3%80%82%E6%89%93%E4%B8%AA%E6%AF%94%E6%96%B9%EF%BC%8C%E8%BF%99%E5%B0%B1%E5%A6%82%E5%90%8C%E5%8D%95%E7%9B%B8%E6%80%9D%E7%9A%84%E6%84%9F%E8%A7%89%EF%BC%8C%E6%98%8E%E7%9F%A5%E6%81%8B%E6%83%85%E4%B8%8D%E4%BC%9A%E6%9C%89%E7%BB%93%E6%9E%9C%EF%BC%8C%E5%8D%B4%E8%BF%98%E6%98%AF%E5%BF%98%E4%B8%8D%E4%BA%86%E5%AF%B9%E6%96%B9\n",
      "test on Web Browserhttp://tsn.baidu.com/text2audio?tok=24.66ac2660b6c4ff5d2c3ecb91f9303125.2592000.1607936745.282335-22971991&tex=%25E5%2585%25B6%25E5%25AE%259E%25E5%25BE%2588%25E4%25B9%2585%25E4%25BB%25A5%25E5%2589%258D%25E6%2588%2591%25E5%25B0%25B1%25E7%259F%25A5%25E9%2581%2593%25E8%2587%25AA%25E5%25B7%25B1%25E5%25BA%2594%25E8%25AF%25A5%25E6%2580%258E%25E6%25A0%25B7%25E9%2580%2589%25E6%258B%25A9%25EF%25BC%258C%25E5%258F%25AA%25E6%2598%25AF%25E4%25B8%2580%25E7%259B%25B4%25E6%2597%25A0%25E6%25B3%2595%25E4%25B8%258B%25E5%2586%25B3%25E5%25BF%2583%25E8%2588%258D%25E5%25BC%2583%25E6%25A2%25A6%25E6%2583%25B3%25E3%2580%2582%25E5%2588%25B0%25E7%258E%25B0%25E5%259C%25A8%25EF%25BC%258C%25E6%2588%2591%25E4%25BE%259D%25E7%2584%25B6%25E4%25B8%258D%25E7%259F%25A5%25E9%2581%2593%25E6%2580%258E%25E6%25A0%25B7%25E6%2589%258D%25E8%2583%25BD%25E5%2581%259A%25E5%2588%25B0%25E8%25BF%2599%25E4%25B8%2580%25E7%2582%25B9%25E3%2580%2582%25E6%2589%2593%25E4%25B8%25AA%25E6%25AF%2594%25E6%2596%25B9%25EF%25BC%258C%25E8%25BF%2599%25E5%25B0%25B1%25E5%25A6%2582%25E5%2590%258C%25E5%258D%2595%25E7%259B%25B8%25E6%2580%259D%25E7%259A%2584%25E6%2584%259F%25E8%25A7%2589%25EF%25BC%258C%25E6%2598%258E%25E7%259F%25A5%25E6%2581%258B%25E6%2583%2585%25E4%25B8%258D%25E4%25BC%259A%25E6%259C%2589%25E7%25BB%2593%25E6%259E%259C%25EF%25BC%258C%25E5%258D%25B4%25E8%25BF%2598%25E6%2598%25AF%25E5%25BF%2598%25E4%25B8%258D%25E4%25BA%2586%25E5%25AF%25B9%25E6%2596%25B9&per=106&spd=6&pit=6&vol=6&aue=3&cuid=123456PYTHON&lan=zh&ctp=1\n",
      "result saved as :result.mp3\n"
     ]
    }
   ],
   "source": [
    "# coding=utf-8\n",
    "import sys\n",
    "import json\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "    from urllib.parse import quote_plus\n",
    "else:\n",
    "    import urllib2\n",
    "    from urllib import quote_plus\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "\n",
    "# API_KEY = '4E1BG9lTnlSeIf1NQFlrSq6h'\n",
    "# SECRET_KEY = '544ca4657ba8002e3dea3ac2f5fdd241'\n",
    "\n",
    "TEXT = \"其实很久以前我就知道自己应该怎样选择，只是一直无法下决心舍弃梦想。到现在，我依然不知道怎样才能做到这一点。打个比方，这就如同单相思的感觉，明知恋情不会有结果，却还是忘不了对方\"\n",
    "\n",
    "# 发音人选择, 基础音库：0为度小美，1为度小宇，3为度逍遥，4为度丫丫，\n",
    "# 精品音库：5为度小娇，103为度米朵，106为度博文，110为度小童，111为度小萌，默认为度小美 \n",
    "PER = 106\n",
    "# 语速，取值0-15，默认为5中语速\n",
    "SPD = 5\n",
    "# 音调，取值0-15，默认为5中语调\n",
    "PIT = 6\n",
    "# 音量，取值0-9，默认为5中音量\n",
    "VOL = 6\n",
    "# 下载的文件格式, 3：mp3(default) 4： pcm-16k 5： pcm-8k 6. wav\n",
    "AUE = 3\n",
    "\n",
    "FORMATS = {3: \"mp3\", 4: \"pcm\", 5: \"pcm\", 6: \"wav\"}\n",
    "FORMAT = FORMATS[AUE]\n",
    "\n",
    "CUID = \"123456PYTHON\"\n",
    "\n",
    "TTS_URL = 'http://tsn.baidu.com/text2audio'\n",
    "\n",
    "\n",
    "class DemoError(Exception):\n",
    "    pass\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN start \"\"\"\n",
    "\n",
    "TOKEN_URL = 'http://openapi.baidu.com/oauth/2.0/token'\n",
    "SCOPE = 'audio_tts_post'  # 有此scope表示有tts能力，没有请在网页里勾选\n",
    "\n",
    "\n",
    "def fetch_token():\n",
    "    print(\"fetch token begin\")\n",
    "    params = {'grant_type': 'client_credentials',\n",
    "              'client_id': API_KEY,\n",
    "              'client_secret': SECRET_KEY}\n",
    "    post_data = urlencode(params)\n",
    "    if (IS_PY3):\n",
    "        post_data = post_data.encode('utf-8')\n",
    "    req = Request(TOKEN_URL, post_data)\n",
    "    try:\n",
    "        f = urlopen(req, timeout=5)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "        print('token http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    if (IS_PY3):\n",
    "        result_str = result_str.decode()\n",
    "\n",
    "    print(result_str)\n",
    "    result = json.loads(result_str)\n",
    "    print(result)\n",
    "    if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "        if not SCOPE in result['scope'].split(' '):\n",
    "            raise DemoError('scope is not correct')\n",
    "        print('SUCCESS WITH TOKEN: %s ; EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN end \"\"\"\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    token = fetch_token()\n",
    "    print(\"这是token:\",token)\n",
    "    tex = quote_plus(TEXT)  # 此处TEXT需要两次urlencode\n",
    "    print(\"这是tex:\",tex)\n",
    "    params = {'tok': token, 'tex': tex, 'per': PER, 'spd': SPD, 'pit': PIT, 'vol': VOL, 'aue': AUE, 'cuid': CUID,\n",
    "              'lan': 'zh', 'ctp': 1}  # lan ctp 固定参数\n",
    "\n",
    "    data = urlencode(params)\n",
    "    print('test on Web Browser' + TTS_URL + '?' + data)\n",
    "\n",
    "    req = Request(TTS_URL, data.encode('utf-8'))\n",
    "    has_error = False\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "\n",
    "        headers = dict((name.lower(), value) for name, value in f.headers.items())\n",
    "\n",
    "        has_error = ('content-type' not in headers.keys() or headers['content-type'].find('audio/') < 0)\n",
    "    except  URLError as err:\n",
    "        print('asr http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "        has_error = True\n",
    "\n",
    "    save_file = \"error.txt\" if has_error else 'result.' + FORMAT\n",
    "    with open(save_file, 'wb') as of:\n",
    "        of.write(result_str)\n",
    "\n",
    "    if has_error:\n",
    "        if (IS_PY3):\n",
    "            result_str = str(result_str, 'utf-8')\n",
    "        print(\"tts api  error:\" + result_str)\n",
    "\n",
    "    print(\"result saved as :\" + save_file)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### B-1 moviepy 视频转换音频\n",
    "\n",
    "* [moviepy文档](https://zulko.github.io/moviepy/ref/AudioClip.html?highlight=subclip#moviepy.audio.AudioClip.CompositeAudioClip.subclip)\n",
    "* [moviepy模块使用教程](https://blog.csdn.net/ucsheep/article/details/80999939)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\r",
      "chunk:   0%|                                                                         | 0/557 [00:00<?, ?it/s, now=None]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "MoviePy - Writing audio in result01.mp3\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "                                                                                                                       "
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "MoviePy - Done.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\r"
     ]
    }
   ],
   "source": [
    "# B-1\n",
    "import moviepy.editor as mp\n",
    "clip = mp.VideoFileClip(\"practice.mp4\")\n",
    "# print(clip)\n",
    "clip.audio.write_audiofile(\"result01.mp3\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### B-2 计算音频时间 duration"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "25.22"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# B-2 clip.duration计算video时间(秒)\n",
    "clip.duration"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 音频剪辑（拆分）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "chunk:  43%|██████████████████████████▏                                  | 558/1301 [01:19<00:01, 674.27it/s, now=None]\n",
      "chunk:   0%|                                                                         | 0/331 [00:00<?, ?it/s, now=None]\u001b[A"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "MoviePy - Writing audio in result02.mp3\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "chunk:   9%|█████▌                                                         | 29/331 [00:00<00:01, 257.33it/s, now=None]\u001b[A\n",
      "chunk:  41%|█████████████████████████▍                                    | 136/331 [00:00<00:00, 333.03it/s, now=None]\u001b[A\n",
      "chunk:  76%|██████████████████████████████████████████████▊               | 250/331 [00:00<00:00, 422.48it/s, now=None]\u001b[A\n",
      "chunk:  98%|█████████████████████████████████████████████████████████████ | 326/331 [00:00<00:00, 486.73it/s, now=None]\u001b[A\n",
      "chunk:  43%|██████████████████████████▏                                  | 558/1301 [01:20<00:01, 674.27it/s, now=None]\u001b[A"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "MoviePy - Done.\n"
     ]
    }
   ],
   "source": [
    "# B-3\n",
    "import moviepy.editor as mp\n",
    "clip = mp.VideoFileClip(\"practice.mp4\")\n",
    "newclip = clip.subclip(t_start=10,t_end=25)\n",
    "newclip.audio.write_audiofile('result02.mp3')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### B-4批量剪辑整段音频\n",
    "\n",
    "```\n",
    "path = '../_week08_/audio/'\n",
    "i = 0\n",
    "while True:\n",
    "    clip = mp.VideoFileClip(\"04301846.mp4\")\n",
    "    newclip = clip.subclip(t_start =(i) ,t_end = (i+59))\n",
    "    newclip.audio.write_audiofile(path+\"theaudio_\"+str(i)+\".mp3\")\n",
    "    i +=60\n",
    "#     print(newclip.duration)\n",
    "    if i > clip.duration:  \n",
    "        break \n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### B-5 mp3转换为API识别的格式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# B-5\n",
    "# 转换多个文件\n",
    "import os\n",
    "movie_name = os.listdir('../_week08_/audio/')\n",
    "for temp in movie_name:\n",
    "    print(temp.split('.')[0]+'.m4a')\n",
    "    new_name = temp.split('.')[0]+'.m4a'\n",
    "    os.rename('../_week08_/audio/'+temp,'../_week08_/audio/'+new_name)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "ename": "FileNotFoundError",
     "evalue": "[WinError 3] 系统找不到指定的路径。: '../result02.mp3'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mFileNotFoundError\u001b[0m                         Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-15-3d6d73ecea1f>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m      9\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     10\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mos\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 11\u001b[1;33m \u001b[0mmovie_name\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mos\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mlistdir\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'../result02.mp3'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     12\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mmovie_name\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0msplit\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'.'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m+\u001b[0m\u001b[1;34m'.m4a'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     13\u001b[0m \u001b[1;31m# new_name = movie_name.split('.')[0]+'.m4a'\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mFileNotFoundError\u001b[0m: [WinError 3] 系统找不到指定的路径。: '../result02.mp3'"
     ]
    }
   ],
   "source": [
    "# 转换单个文件\n",
    "\n",
    "'''\n",
    "“./”：代表目前所在的目录。\n",
    "“.../”：代表上一层目录。\n",
    "“/”：代表根目录。\n",
    "“../” ：表示父级路径，当前路径所在的上一级路径。\n",
    "'''\n",
    "\n",
    "import os\n",
    "movie_name = os.listdir('../result02.mp3')\n",
    "print(movie_name.split('.')[0]+'.m4a')\n",
    "# new_name = movie_name.split('.')[0]+'.m4a'\n",
    "# os.rename('result02.m4a','result03.m4a')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 调用百度API :实现video—text"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# coding=utf-8\n",
    "\n",
    "import sys\n",
    "import json\n",
    "import time\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "\n",
    "    timer = time.perf_counter\n",
    "else:\n",
    "    import urllib2\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "\n",
    "    if sys.platform == \"win32\":\n",
    "        timer = time.clock\n",
    "    else:\n",
    "        # On most other platforms the best timer is time.time()\n",
    "        timer = time.time\n",
    "\n",
    "API_KEY = 'kVcnfD9iW2XVZSMaLMrtLYIz'\n",
    "SECRET_KEY = 'O9o1O213UgG5LFn0bDGNtoRN3VWl2du6'\n",
    "\n",
    "# for audio_file in os.listdir(path):\n",
    "#     # 需要识别的文件\n",
    "#     AUDIO_FILE = './rest-api-asr/python/audio/liao_audio/'+audio_file # 只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "#     # 文件格式\n",
    "#     FORMAT = AUDIO_FILE[-3:];  # 文件后缀只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "\n",
    "CUID = '123456PYTHON';\n",
    "# 采样率\n",
    "RATE = 16000;  # 固定值\n",
    "\n",
    "# 普通版\n",
    "\n",
    "DEV_PID = 1537;  # 1537 表示识别普通话，使用输入法模型。根据文档填写PID，选择语言及识别模型\n",
    "ASR_URL = 'http://vop.baidu.com/server_api'\n",
    "SCOPE = 'audio_voice_assistant_get'  # 有此scope表示有asr能力，没有请在网页里勾选，非常旧的应用可能没有\n",
    "\n",
    "#测试自训练平台需要打开以下信息， 自训练平台模型上线后，您会看见 第二步：“”获取专属模型参数pid:8001，modelid:1234”，按照这个信息获取 dev_pid=8001，lm_id=1234\n",
    "# DEV_PID = 8001 ;   \n",
    "# LM_ID = 1234 ;\n",
    "\n",
    "# 极速版 打开注释的话请填写自己申请的appkey appSecret ，并在网页中开通极速版（开通后可能会收费）\n",
    "\n",
    "#DEV_PID = 80001\n",
    "#ASR_URL = 'http://vop.baidu.com/pro_api'\n",
    "#SCOPE = 'brain_enhanced_asr'  # 有此scope表示有asr能力，没有请在网页里开通极速版\n",
    "\n",
    "# 忽略scope检查，非常旧的应用可能没有\n",
    "# SCOPE = False\n",
    "\n",
    "\n",
    "# 极速版\n",
    "\n",
    "class DemoError(Exception):\n",
    "    pass\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN start \"\"\"\n",
    "\n",
    "TOKEN_URL = 'http://openapi.baidu.com/oauth/2.0/token'\n",
    "\n",
    "\n",
    "def fetch_token():\n",
    "    params = {'grant_type': 'client_credentials',\n",
    "              'client_id': API_KEY,\n",
    "              'client_secret': SECRET_KEY}\n",
    "    post_data = urlencode(params)\n",
    "    if (IS_PY3):\n",
    "        post_data = post_data.encode('utf-8')\n",
    "    req = Request(TOKEN_URL, post_data)\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "        print('token http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    if (IS_PY3):\n",
    "        result_str = result_str.decode()\n",
    "\n",
    "    print(result_str)\n",
    "    result = json.loads(result_str)\n",
    "    print(result)\n",
    "    if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "        if SCOPE and (not SCOPE in result['scope'].split(' ')):  # SCOPE = False 忽略检查\n",
    "            raise DemoError('scope is not correct')\n",
    "        print('SUCCESS WITH TOKEN: %s ; EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN end \"\"\"\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    token = fetch_token()\n",
    "\n",
    "    \"\"\"\n",
    "    httpHandler = urllib2.HTTPHandler(debuglevel=1)\n",
    "    opener = urllib2.build_opener(httpHandler)\n",
    "    urllib2.install_opener(opener)\n",
    "    \"\"\"\n",
    "    for audio_file in os.listdir(path):\n",
    "        # 需要识别的文件\n",
    "        AUDIO_FILE = '../_week08_/audio/'+audio_file # 只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "        # 文件格式\n",
    "        FORMAT = AUDIO_FILE[-3:];  # 文件后缀只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "        speech_data = []\n",
    "        with open(AUDIO_FILE, 'rb') as speech_file:\n",
    "            speech_data = speech_file.read()\n",
    "        length = len(speech_data)\n",
    "        if length == 0:\n",
    "            raise DemoError('file %s length read 0 bytes' % AUDIO_FILE)\n",
    "\n",
    "        params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID}\n",
    "        #测试自训练平台需要打开以下信息\n",
    "        #params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID, 'lm_id' : LM_ID}\n",
    "        params_query = urlencode(params);\n",
    "\n",
    "        headers = {\n",
    "            'Content-Type': 'audio/' + FORMAT + '; rate=' + str(RATE),\n",
    "            'Content-Length': length\n",
    "        }\n",
    "\n",
    "        url = ASR_URL + \"?\" + params_query\n",
    "        print(\"url is\", url);\n",
    "        print(\"header is\", headers)\n",
    "        # print post_data\n",
    "        req = Request(ASR_URL + \"?\" + params_query, speech_data, headers)\n",
    "        try:\n",
    "            begin = timer()\n",
    "            f = urlopen(req)\n",
    "            result_str = f.read()\n",
    "            print(\"Request time cost %f\" % (timer() - begin))\n",
    "        except  URLError as err:\n",
    "            print('asr http response http code : ' + str(err.code))\n",
    "            result_str = err.read()\n",
    "\n",
    "        if (IS_PY3):\n",
    "            result_str = str(result_str, 'utf-8')\n",
    "        print(result_str)\n",
    "        with open(\"../_week08_/text/\"+audio_file[0:-4]+\".txt\", \"w\") as of:\n",
    "            of.write(result_str)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
